package com.xqx.dao.impl;

import com.xqx.dao.UserDao;
import com.xqx.domain.Role;
import com.xqx.domain.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataAccessException;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Repository;

import java.util.List;

/**
 * @author：xingquanxiang createTime：2019/10/5 13:32
 * description:
 */
@Repository("userDao")
public class UserDaoImpl implements UserDao {
    @Autowired
    private JdbcTemplate jdbcTemplate;
    /**
     * 查询所有用户
     *
     * @return
     */
    @Override
    public List<User> findAll()throws DataAccessException {
        return jdbcTemplate.query("select * from sys_user", new BeanPropertyRowMapper<User>(User.class));
    }

    /**
     * 根据id删除用户信息
     *
     * @param id
     * @return 返回影响行数
     */
    @Override
    public int del(int id) {
        System.out.println("id = " + id);
        jdbcTemplate.update("delete from sys_user_role where userId=?", id);
        return jdbcTemplate.update("delete from sys_user where id=?", id);
    }

    /**
     * 根据用户id查询用户角色
     *
     * @param id
     * @return
     */
    @Override
    public List<Role> findRoleByUserId(Long id) throws DataAccessException{
        return jdbcTemplate.query("select * from sys_user_role ur, sys_role r where ur.roleId=r.id and ur.userId=?",
                new BeanPropertyRowMapper<Role>(Role.class), id);
    }
}
